package cn.schoolwow.quickdao.module.database.dml.json.flow.insert.get;

import cn.schoolwow.quickdao.domain.QuickDAOConfig;
import cn.schoolwow.quickdao.module.database.dml.common.domain.ManipulationOption;
import cn.schoolwow.quickdao.module.database.parent.domain.ResultSetConsumer;
import cn.schoolwow.quickdao.module.database.parent.flow.executor.ExecuteQueryConnectionFlow;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import com.alibaba.fastjson.JSONObject;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class GetCountByUniqueFieldFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        setStatement(flowContext);
        setParameters(flowContext);
        executeStatement(flowContext);
    }

    @Override
    public String name() {
        return "根据唯一约束列查询记录个数";
    }

    private void setStatement(FlowContext flowContext) {
        QuickDAOConfig quickDAOConfig = flowContext.checkInstanceData(QuickDAOConfig.class);
        String tableName = (String) flowContext.checkData("tableName");
        ManipulationOption manipulationOption = flowContext.checkInstanceData(ManipulationOption.class);
        
        StringBuilder sqlBuilder = new StringBuilder("select count(1) from " + quickDAOConfig.databaseContext.databaseProvider.escape(tableName) + " where");
        for(String fieldName:manipulationOption.uniqueFieldNames){
            sqlBuilder.append(" " + quickDAOConfig.databaseContext.databaseProvider.escape(fieldName) + " = ? and");
        }
        sqlBuilder.delete(sqlBuilder.length()-4,sqlBuilder.length());
        flowContext.putTemporaryData("sql", sqlBuilder.toString());
    }

    private void setParameters(FlowContext flowContext){
        ManipulationOption manipulationOption = flowContext.checkInstanceData(ManipulationOption.class);
        JSONObject instance = (JSONObject) flowContext.checkData("instance");

        List<Object> parameters = new ArrayList();
        for(String fieldName:manipulationOption.uniqueFieldNames){
            parameters.add(instance.get(fieldName));
        }
        flowContext.putTemporaryData("parameters", parameters);
    }

    private void executeStatement(FlowContext flowContext){
        flowContext.startFlow(new ExecuteQueryConnectionFlow())
                .putTemporaryData("name", "根据指定列查询记录个数")
                .putReturnData("resultSetConsumer",new ResultSetConsumer() {
                    @Override
                    public void consumeResultSet(ResultSet resultSet) throws Exception {
                        if(resultSet.next()){
                            flowContext.putData("count", resultSet.getLong(1));
                        }
                    }
                })
                .execute();
    }
}
